package com.taotao.search.service.imp;

import java.util.List;

import javax.annotation.Resource;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.common.utils.ExceptionUtil;
import com.taotao.common.utils.TaotaoResult;
import com.taotao.search.mapper.ItemMapper;
import com.taotao.search.pojo.Item;
import com.taotao.search.service.ItemService;

@Service
public class ItemServiceImp implements ItemService {

    private static Logger logger = LoggerFactory.getLogger(ItemServiceImp.class);

    @Autowired
    private ItemMapper itemMapper;
    
    @Resource(name = "httpSolrServer")
    private SolrServer solrServer;

    @Override
    public TaotaoResult importItemAll() {
        try {
            // 查询商品
            List<Item> list = itemMapper.searchItemList();
            for (Item item : list) {
                // 创建SolrInputDocument对象
                SolrInputDocument solrInputDocument = new SolrInputDocument();
                solrInputDocument.setField("id", item.getId());
                solrInputDocument.setField("item_title", item.getTitle());
                solrInputDocument.setField("item_sell_point", item.getSellPoint());
                solrInputDocument.setField("item_price", item.getPrice());
                solrInputDocument.setField("item_image", item.getImage());
                solrInputDocument.setField("item_category_name", item.getCategoryName());
                solrInputDocument.setField("item_desc", item.getItemDescribe());
                // 写入索引库
                solrServer.add(solrInputDocument);
            }
            // 提交修改
            solrServer.commit();
        } catch (Exception e) {
            logger.error("solr commit failed", e);
            return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
        }
        return TaotaoResult.ok();
    }
}
